/**
 * 键盘控制系列
 */
import { keyboard } from './keyboard';

let spirit, state;
export const control = (gl, app, robot, emit) => {
  spirit = robot
  // 键盘控制精灵
  let left = keyboard(37),
    up = keyboard(38),
    right = keyboard(39),
    down = keyboard(40);

  //向zuo
  left.press = () => {
    emit('left')
    // 按键时改变机器人的速度
    robot.vx = -1;
    robot.vy = 0;
  };

  left.release = () => {
    if (!right.isDown && robot.vy === 0) {
      robot.vx = 0;
    }
  };

  //向上
  up.press = () => {
    emit('up')
    robot.vy = -1;
    robot.vx = 0;
  };

  up.release = () => {
    if (!down.isDown && robot.vx === 0) {
      robot.vy = 0;
    }
  };

  //向右
  right.press = () => {
    emit('right')
    robot.vx = 1;
    robot.vy = 0;
  };

  right.release = () => {
    if (!left.isDown && robot.vy === 0) {
      robot.vx = 0;
    }
  };

  //向下
  down.press = () => {
    emit('down')
    robot.vy = 1;
    robot.vx = 0;
  };

  down.release = () => {
    if (!up.isDown && robot.vx === 0) {
      robot.vy = 0;
    }
  };

  // 设置游戏状态
  state = play;

  // 开始游戏循环，容器中无法循环动画
  gl.ticker.add(delta => gameLoop(delta));
}


function gameLoop (delta) {
  // 更新当前游戏状态
  state(delta);
}

function play () {
  // 利用机器人的速度使其移动
  spirit.x += spirit.vx;
  spirit.y += spirit.vy
}